package com.esl.coordinator.test.socketserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleServer {
	static final Logger LOG = LoggerFactory.getLogger(SimpleServer.class);

	private int serverPort = 0;
	private ServerSocket serverSock = null;
	private Socket sock = null;

	public SimpleServer(int serverPort) throws IOException {
		this.serverPort = serverPort;

		serverSock = new ServerSocket(serverPort);
	}

	public void waitForConnections() {
		while (true) {
			try {
				sock = serverSock.accept();
				LOG.info("SimpleServer: Accepted new socket, creating new handler for it.");
				SimpleHandler handler = new SimpleHandler(sock);
				handler.start();
				LOG.info("SimpleServer: Finished with socket, waiting for next connection.");
			} catch (IOException e) {
				LOG.error(e.getMessage(), e);
				try {
					serverSock = new ServerSocket(serverPort);
				} catch (IOException e1) {
					LOG.error(e.getMessage(), e);
				}
			}
		}
	}

	public static void main(String argv[]) {
		int port = 9999;

		SimpleServer server = null;
		try {
			server = new SimpleServer(port);
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		}
		server.waitForConnections();
	}
}
